package com.hinner.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.ObjectMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hinner.entity.User;
import com.hinner.entity.WxUser;
import com.hinner.entity.vo.WeChatSession;
import com.hinner.exception.CustomException;
import com.hinner.exception.GlobalExceptionHandler;
import com.hinner.mapper.WxUserMapper;
import com.hinner.service.WxUserService;
import com.hinner.utils.WeChatDecryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;

@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements WxUserService {
    private static final Logger log = LoggerFactory.getLogger(WxUserServiceImpl.class);

    @Autowired
    private WxUserMapper wxUserMapper;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;

    public WeChatSession getSessionKey(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                +appid+"&secret="
                +secret+"&js_code="
                + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        if (response.contains("errCode")){
            throw new CustomException("获取sessionKey失败 : "+ response);
        }
        WeChatSession weChatSession = JSONUtil.toBean(response, WeChatSession.class);
        return weChatSession;
    }

    // 解密用户信息
    public WxUser decryptUserInfo(String encryptedData, String sessionKey, String iv) throws Exception {
        // 解码
        byte[] key = Base64.decode(sessionKey);
        byte[] data = Base64.decode(encryptedData);
        byte[] ivBytes = Base64.decode(iv);

        // 解密
        String decryptStr = WeChatDecryptUtil.decryptWeChatUserInfo(encryptedData, iv, sessionKey);
        return JSON.parseObject(decryptStr, WxUser.class);
    }



    @Override
    public WxUser findByOpenId(String openId) {
        return this.getOne(new QueryWrapper<WxUser>().eq("open_id", openId));
    }

}
